// 封装请求
import {
  config
} from './config.js'

const tips = {
  1001: '抱歉，出现了一个错误',
  1002: 'url路径错误',
  // ...
}

class HTTP {
  // 必填参数在默认值参数前面
  // 对象解构
  request({
    url,
    data = {},
    method = 'GET'
  }) {
    return new Promise((resolve, reject) => {
      this._request(url, resolve, reject, data, method)
    })
  }

  _request(url, resolve, reject, data = {}, method = 'GET') {
    const sessionId = wx.getStorageSync('sessionId')
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
    } // 设置请求的 header
    if (sessionId) {
      header.sessionId = sessionId
    } 
    else if (url !== 'api/wechat/login') {
      showError('没有sessinId')
      return
    }
    wx.showNavigationBarLoading()
    wx.request({
      url: config.api_base_url + url,
      data: data,
      method: method, // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header, // 设置请求的 header
      success: res => {
        // startsWith  endsWith
        // console.log('请求回包', res)
        const code = res.statusCode.toString()
        // 2开头的状态码表示成功
        if (code.startsWith('2')) {
          resolve(res.data)
        } else {
          reject(res)
          let error_code = res.errMsg
          this._show_error(1001)
        }
      },
      fail: err => {
        reject(res)
        this._show_error(1001)
      },
      complete: function () {
        // complete
        wx.hideNavigationBarLoading()
      }
    })
  }

  _show_error(error_code = 1001) {
    const tip = tips[error_code]
    wx.showToast({
      title: tip ? tip : tips[1001],
      icon: 'none',
      duration: 2000
    })
  }
}

// 模态弹窗
export function showModal(title, content) {
  wx.showModal({
    title,
    content,
    showCancel: false
  })
}
// 成功提示框
export function showSuccess(message) {
  wx.showToast({
    title: message,
    icon: 'success'
  })
}
// 错误提示框
export function showError(message) {
  wx.showToast({
    title: message,
    image: '/images/prompt.png',
    duration: 900
  })
}



export {
  HTTP
}